package org.example.sensor.controller;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.example.sensor.dto.ChatMessage;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.io.ByteArrayOutputStream;

@RestController
@RequestMapping("/api/ai")
public class ChatController2 {
    private final ChatClient chatClient;

    // 构造方法注入 ChatClient.Builder，用于构建 ChatClient 实例
    public ChatController2(ChatClient.Builder chatClient) {
        this.chatClient = chatClient.build();
    }

    @PostMapping("/chat")
    public ResponseEntity<Flux<String>> chat( @RequestBody ChatMessage message) {
        try {
            // 调用 ChatClient 生成响应，并以 Flux<String>（响应流）形式返回
            Flux<String> response = chatClient.prompt(message.getContent()).stream().content();
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    @PostMapping("/chat/to-doc")
    public ResponseEntity<byte[]> chatToDoc(@RequestBody ChatMessage message) {
        try {
            // 调用 ChatClient 生成响应
            Flux<String> response = chatClient.prompt(message.getContent()).stream().content();
            // 收集响应内容
            StringBuilder content = new StringBuilder();
            response.subscribe(content::append);

            // 创建 Word 文档
            XWPFDocument document = new XWPFDocument();
            XWPFParagraph paragraph = document.createParagraph();
            XWPFRun run = paragraph.createRun();
            run.setText(content.toString());

            // 将文档写入字节数组输出流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            document.write(baos);
            byte[] docBytes = baos.toByteArray();

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "chat_history.docx");

            return new ResponseEntity<>(docBytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

}
